﻿using GalaSoft.MvvmLight.Threading;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using TYBase;
using TYControl;
using TYRTUBase;
using TYRTUBase.Comm;

namespace TYControl_For_RTU
{
    public partial class View_Config_Device_IR : TYUserControl
    {
        private ViewModel_Config_Device_IR vm = new ViewModel_Config_Device_IR();
        private Device_IR m_IR;

        public View_Config_Device_IR(Device_IR ir, System.Collections.ObjectModel.ObservableCollection<ViewModelComBase> listComInfo)
        {
            InitializeComponent();
            this.DataContext = vm;
            vm.ListComModel = listComInfo;
            SetIR(ir);
        }

        private string section = "";

        private void SetIR(Device_IR ir)
        {
            m_IR = ir;
            if (m_IR != null)
            {
                m_IR.OnComDataSend += M_Switch_OnComDataSend;
                m_IR.OnComDataRead += M_Switch_OnComDataRead;
                m_IR.OnCom_Close_Connected += M_IR_OnCom_Close_Connected;

                section = ir.EquipId;
                btnOpenCom.IsEnabled = true;
                btnOpenCom.Content = m_IR.IsConnected ? "关闭" : "打开";
                vm.IsXMode = DataCenter.ini.ReadBoolEx(section, $"{EnumConfig_Device.IsXMode}", false);
                vm.OCV_Min = DataCenter.ini.ReadDouble(section, $"{EnumConfig_Device.OCVMin}", 0);
                vm.OCV_Max = DataCenter.ini.ReadDouble(section, $"{EnumConfig_Device.CVMax}", 0);
                vm.IR_Min = DataCenter.ini.ReadDouble(section, $"{EnumConfig_Device.IRMin}", 0);
                vm.IR_Max = DataCenter.ini.ReadDouble(section, $"{EnumConfig_Device.IRMax}", 0);
                vm.SpeedIndex = DataCenter.ini.ReadIntEx(section, $"{EnumConfig_Device.IRSpeed}", 0);

                var com = DataCenter.ini.ReadIntEx(section, $"{EnumConfig_Device.Com}", 0);
                vm.SelectedCOM = vm.ListComModel.FirstOrDefault(x => x.Com == com);
            }
        }

        private void M_IR_OnCom_Close_Connected(ITYClient sender, bool isConnected)
        {
            if (isConnected)
            {
                AddLog($"串口 {sender.ParaKey()}已打开!");
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    btnOpenCom.Content = "关闭";
                });
            }
            else
            {
                AddLog($"串口 {sender.ParaKey()}已关闭!");
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    btnOpenCom.Content = "打开";
                });
            }
        }

        private void M_Switch_OnComDataRead(ITYClient sender, byte[] data)
        {
            AddLog($"com:{sender.ParaKey()} 读到 hex:{data.AsHexString(' ')} data: {data.AsString()}");
        }

        private void M_Switch_OnComDataSend(ITYClient sender, byte[] data)
        {
            AddLog($"com:{sender.ParaKey()} 发送 hex:{data.AsHexString(' ')} data: {data.AsString()}");
        }

        private void AddLog(string message, bool showMBox = false)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
            {
                edit.AppendText($"{DateTime.Now.ToString("HH:mm:ss")} - {message}{Environment.NewLine}");
                if (showMBox)
                {
                    MessageBox.Show(message);
                    return;
                }
            });
        }

        private void BtnClick_Open_Close(object sender, RoutedEventArgs e)
        {
            if (m_IR == null)
            {
                AddLog($"缓存串口为空!", true);
                return;
            }

            string btnContent = btnOpenCom.Content.ToString();
            if (btnContent == "打开")
            {
                if (vm.SelectedCOM == null)
                {
                    AddLog($"请选择串口", true);
                    return;
                }

                m_IR.Close();
                m_IR.Init(vm.SelectedCOM.Com);
                if (!m_IR.Connect())
                {
                    AddLog($"打开{vm.SelectedCOM.Com}失败!", true);
                    return;
                }
                else
                {
                    AddLog($"打开{vm.SelectedCOM.Com}OK", true);
                    //btnOpenCom.Content = "关闭";
                }
            }
            else
            {
                m_IR.Close();
                //btnOpenCom.Content = "关闭";
            }
        }

        private async void BtnClick_InitIR(object sender, RoutedEventArgs e)
        {
            if (m_IR == null)
            {
                AddLog($"缓存串口为空!", true);
                return;
            }
            AddLog($"开始初始化IR");
            var spd = IRSpedHelper.GetSpeed(vm.SpeedIndex);
            var ret = await Task.Run(() =>
             {
                 return m_IR.InitIR(spd);
             });
            if (ret)
            {
                AddLog($"初始化IR OK ", true);
            }
            else
            {
                AddLog($"初始化IR 失败!!!!! ", true);
            }
        }

        private async void BtnClick_ReadIR(object sender, RoutedEventArgs e)
        {
            if (m_IR == null)
            {
                AddLog($"缓存串口为空!", true);
                return;
            }
            AddLog($"开始读取");
            string data = "";
            var ret = await Task.Run(() =>
            {
                return m_IR.ReadData(out data);
            });
            if (ret)
            {
                AddLog($"读取IR: {data} ");
            }
            else
            {
                AddLog($"读取IR: 失败!!!!! ", true);
            }
        }

        public async Task<bool> SaveIRPara()
        {
            if (vm.SelectedCOM == null)
            {
                AddLog($"请选择串口", true);
                return false;
            }

            var isX = vm.IsXMode;
            if (m_IR != null && section.NotNull())
            {
                AddLog($"**************开始处理******************");
                DataCenter.ini.WriteBool(section, $"{EnumConfig_Device.IsXMode}", isX);
                DataCenter.ini.WriteDouble(section, $"{EnumConfig_Device.OCVMin}", vm.OCV_Min);
                DataCenter.ini.WriteDouble(section, $"{EnumConfig_Device.CVMax}", vm.OCV_Max);
                DataCenter.ini.WriteDouble(section, $"{EnumConfig_Device.IRMin}", vm.IR_Min);
                DataCenter.ini.WriteDouble(section, $"{EnumConfig_Device.IRMax}", vm.IR_Max);
                DataCenter.ini.WriteInt(section, $"{EnumConfig_Device.IRSpeed}", vm.SpeedIndex);

                int com = vm.SelectedCOM.Com;
                DataCenter.ini.WriteInt(section, $"{EnumConfig_Device.Com}", com);
                string error = "";
                var ret = await RunEx(() =>
                 {
                     m_IR.Close();
                     AddLog($"串口 {m_IR.Com} 已关闭!", false);
                     return DataCenter.mDeviceHelper.Init(m_IR, ref error);
                 });
                if (ret)
                {
                    AddLog($"打开串口成功");
                }
                else
                {
                    AddLog($"打开串口失败! {error}");
                }
                AddLog($"###############处理完成###############");
            }
            return true;
        }

        private async void BtnClick_Save(object sender, RoutedEventArgs e)
        {
            //if (!UserConfirmHelper.CheckUserLevel(EnumUserLevel.系统管理员 | EnumUserLevel.设备管理))
            //{
            //    return;
            //}
            await SaveIRPara();
        }

        private void BtnClick_Simulate(object sender, RoutedEventArgs e)
        {
            if (m_IR == null)
            {
                AddLog("缓存 切换板为空!");
                return;
            }

            m_IR.SetIsXMode(vm.IsXMode);
            m_IR.SetXModePara(new XMode_IR_Para { IRMax = vm.IR_Max, IRMin = vm.IR_Min, OCVMax = vm.OCV_Max, OCVMin = vm.OCV_Min });
            AddLog($"切换模拟 : {vm.IsXMode}");
        }
    }
}